import { Node, AudioSource, AudioClip, resources, director } from 'cc';
import { GlobelMgr } from './GlobelMgr';
import { SettingDataMgr } from './SettingDataMgr';

export class AudioMgr {
    private static _inst: AudioMgr;
    public static get instance(): AudioMgr {
        if (this._inst == null) {
            this._inst = new AudioMgr();
        }
        return this._inst;
    }
    private _backgroundAudioSource: AudioSource;
    private _effectAudioSource: AudioSource;
    public init():void{
        let audioNode = new Node();
        audioNode.name = '__audioMgr__';
        GlobelMgr.instance.getPersistentNode().addChild(audioNode);
        // 创建背景音乐音频源
        this._backgroundAudioSource = audioNode.addComponent(AudioSource);
        this._backgroundAudioSource.loop = true;
        // 创建音效音频源
        this._effectAudioSource = audioNode.addComponent(AudioSource);
    }
    public playBackgroundMusic(name: string) {
        if(!SettingDataMgr.instance.musicEnabled || !this._backgroundAudioSource)
        {
            return;
        }
        const url = this.getUrl(name);
        if (url) {
            resources.load(url, AudioClip, (err, clip: AudioClip) => {
                if (err) {
                    console.error(`Error loading background music ${name}: ${err}`);
                    return;
                }
                this._backgroundAudioSource.clip = clip;
                this._backgroundAudioSource.play();
            });
        } else {
            console.error(`Could not find URL for background music ${name}`);
        }
    }

    public playEffect(name: string) {
        if(!SettingDataMgr.instance.soundEnabled|| !this._effectAudioSource)
        {
            return;
        }
        const url = this.getUrl(name);
        if (url) {
            resources.load(url, AudioClip, (err, clip: AudioClip) => {
                if (err) {
                    console.error(`Error loading effect ${name}: ${err}`);
                    return;
                }
                this._effectAudioSource.playOneShot(clip);
            });
        } else {
            console.error(`Could not find URL for effect ${name}`);
        }
    }
    public resumeBgMusic():void{
        if (this._backgroundAudioSource) {
            this._backgroundAudioSource.play();
        }
    }
     public stopBgMusic() {
        if (this._backgroundAudioSource) {
            this._backgroundAudioSource.pause()
        }
    }

    public stopEffects() {
        if (this._effectAudioSource) {
            this._effectAudioSource.stop();
        }
    }
    private  getUrl(name: string):string{
       return "sound/"+name;
    }
}